package com.isias.system.Controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.isias.common.result.Result;
import com.isias.system.Config.WenJianConfig;
import com.isias.system.Service.IAuthenticationFacade;
import com.isias.common.util.MD5;
import com.isias.model.system.SysUser;
import com.isias.model.vo.SysUserQueryVo;
import com.isias.system.QiniuCloud.QiniuCloudUtil;
import com.isias.system.annotation.Log;
import com.isias.system.enums.BusinessType;
import com.isias.system.service.SysUserService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.Principal;
import java.util.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author fanyi
 * @since 2023-02-19
 */
@RestController
@RequestMapping("/admin/system/sysUser")
public class SysUserController {
    @Autowired
    SysUserService sysUserService;

    @Autowired
    private IAuthenticationFacade authenticationFacade; //获取当前用户对象类

    /**
     * 更改用户状态
     */
    @GetMapping("updataStatus/{id}/{status}")
    public Result updataStatus(@PathVariable String id, @PathVariable Integer status) {
        if (sysUserService.updataStatus(id, status)) {
            return Result.ok(true);
        } else {
            return Result.fail(false);
        }
    }

    /**
     * 分页查询
     */
    Page<SysUser> pageparam = new Page<>();

    @GetMapping("{page}/{limit}")
    public Result SeletePage(@PathVariable Integer page, @PathVariable Integer limit, SysUserQueryVo sysUserQueryVo) {
//        Page<SysUser> pageparam = new Page<>(page,limit);
        pageparam.setCurrent(page);
        pageparam.setSize(limit);
        IPage<SysUser> iPage = sysUserService.SeletePage(pageparam, sysUserQueryVo);
        return Result.ok(iPage);


    }

    /**
     * 给用户分配身份
     *
     * @param id
     * @param postid
     * @return
     */
    @GetMapping("/savePost/{id}/{postid}")
    public Result SavePost(@PathVariable String id, @PathVariable String postid) {
        if (sysUserService.savePost(id, postid)) {
            return Result.ok();
        }
        return Result.fail();

    }

    /***
     * 给用户分配班级
     */
    @GetMapping("/doAssign/{userId}/{deptId}")
    public Result doAssign(@PathVariable String userId, @PathVariable String deptId) {
        if (sysUserService.doAssign(userId, deptId)) {
            return Result.ok();
        }
        return Result.fail();
    }


    /**
     * 获取单个用户
     */

    @GetMapping("{id}")
    public Result SelectById(@PathVariable String id) {
        SysUser user = sysUserService.getById(id);
        return Result.ok(user);

    }

    /**
     * 获取全部用户
     */
    @GetMapping
    public Result SelectAll() {
        List<SysUser> list = sysUserService.list(null);
        return Result.ok(list);

    }

    /**
     * 添加用户-顺带分配默认权限
     */
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Result AddUser(@RequestBody SysUser sysUser) {
        //MD5加密处理用户密码
        String password_md5 = MD5.encrypt(sysUser.getPassword());
        sysUser.setPassword(password_md5);
        if (sysUserService.saveUser(sysUser)) {
            return Result.ok(true);
        } else {
            return Result.fail(false);
        }
    }

    /**
     * 通过id删除用户
     */
    @DeleteMapping("{id}")
    public Result DeleteById(@PathVariable String id) {
        if (sysUserService.removeById(id)) {
            return Result.ok(true);
        } else {
            return Result.fail(false);
        }
    }

    /**
     * 通过id批量删除
     */
    @DeleteMapping("/batchRemove")
    public Result DeleteByIDS(@RequestBody List<String> ids) {
        if (sysUserService.removeByIds(ids)) {
            return Result.ok(true);
        } else {
            return Result.fail(false);
        }
    }

    /**
     * 修改
     */
    @PutMapping()
    public Result Updata(@RequestBody SysUser sysUser) {
        if (sysUserService.updateById(sysUser)) {
            return Result.ok(true);
        } else {
            return Result.fail(false);
        }
    }

    @PostMapping("/uploadImg")
    public Result uploadImg(@RequestBody MultipartFile file, Principal principal) {
        if (file.isEmpty()) {
            return Result.build(null, 3000, "文件不能为空");
        }
        String username = principal.getName();      //通过该对象能够获取到用户名
        try {
            byte[] bytes = file.getBytes();
            String imageName = UUID.randomUUID().toString();
            try {
                //使用base64方式上床到七牛云
                String url = QiniuCloudUtil.put64image(bytes, imageName);
                //地址储存到用户url里
                if (sysUserService.updataHeadUrl(username, url)) {
                    System.out.println(url);
                    return Result.ok(url);
                }
            } catch (Exception e) {
                throw new RuntimeException();
            }
        } catch (IOException e) {
            return Result.build(null, 3001, "上传图片异常");
        }
        return Result.fail();
    }

    @PostMapping("/avatar")
    public Result<Map<String, Object>> avatar(MultipartFile file) throws IOException {
        // 获取当前登录用户
        Authentication authentication = authenticationFacade.getAuthentication();
        String username = authentication.getName();
//        SysUser sysUser = sysUserService.GetUserByusername(username);
        // 文件名称  时间日期+文件名_uuid+后缀
        String fileName = StrUtil.format("{}/{}_{}.{}", DateUtil.format(DateUtil.date(), "yyy/MM/dd"), FilenameUtils.getBaseName(file.getOriginalFilename()), DateUtil.format(new Date(), "yyyyMMdd") + IdUtil.fastUUID(), FilenameUtils.getExtension(file.getOriginalFilename()));
        // 父目录
        String baseDir = WenJianConfig.getAvatarPath();
        //路径拼接
        File desc = new File(baseDir + File.separator + fileName);
        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        // 下载
        file.transferTo(desc);
        int dirLastIndex = WenJianConfig.getProfile().length() + 1;
        // 截取upload/下的名称存入数据库
        String currentDir = baseDir.substring(dirLastIndex);

        String avatar = WenJianConfig.getUrl() + currentDir + "/" + fileName;
        // 修改数据库中的头像路径
        sysUserService.updataHeadUrl(username, avatar);
        Map<String, Object> map = new HashMap<>();
        // 将头像路径返回，这里是为了头像上传后有一个回显的效果
        map.put("imgUrl", avatar);
//        // 将缓存中的对象信息进行一个更新
//        sysUser.getUser().setAvatar(avatar);
//        tokenUtil.setLoginUser(sysUser);
        return Result.ok(map);
    }


}


